//
// Created by ChenYulu on 2017/4/6.
//

#include "threshold.h"

int threshold(Bitmap *src) {
  int width = src->width;
  int height = src->height;
  int pixelCount[256] = {0};
  float pixelPro[256] = {0};
  int i, j, pixelSum = width * height, threshold = 0;
  unsigned char *data = (unsigned char *) src->imageData;
  float w0, w1, u0tmp, u1tmp, u0, u1, deltaTmp, deltaMax = 0;

  //计算每个灰度级中像素的个数
  for (int i = 0; i < height; i++) {
    for (j = 0; j < width; j++) {
      pixelCount[(int) data[i * width + j]]++;
    }
  }

  //计算每个灰度级的像素占整个图像的比例
  for (int i = 0; i < 256; i++) {
    pixelPro[i] = (float) pixelCount[i] / pixelSum;
  }

  //遍历求阈值
  for (int i = 0; i < 256; i++) {
    w0 = w1 = u0tmp = u1tmp = u0 = u1 = deltaTmp = 0;
    for (int j = 0; j < 256; ++j) {
      if (j <= i) {//背景
        w0 += pixelPro[j];
        u0tmp += j * pixelPro[j];
      } else {//前景
        w1 += pixelPro[j];
        u1tmp += j * pixelPro[j];
      }
    }
    u0 = u0tmp / w0;
    u1 = u1tmp / w1;
    deltaTmp = (float) (w0 * w1 * pow((u0 - u1), 2));
    if (deltaTmp > deltaMax) {
      deltaMax = deltaTmp;
      threshold = i;
    }
  }

  return threshold;
}